package com.katze.boot.plugins.security.handle;

import com.katze.common.ResponseStatus;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 统一处理认证失败
        //方法1
//        Object exception = request.getAttribute("jakarta.servlet.error.exception");
//        if (exception instanceof JwtAuthenticationException e) {
//            response.setStatus(e.getStatus());
//            response.getWriter().write("{\"code\":" + e.getStatus() + ",\"type\":\"error\",\"message\":\"" + e.getMessage() + "\"}");
//        }
        //方法2
        int code = response.getStatus();
        if (code == 200) {
            response.setStatus(ResponseStatus.FORBIDDEN.value());
            response.getWriter().write("{\"code\":403,\"type\":\"error\",\"message\":\"用户认证失败\"}");
        } else {
            response.setStatus(ResponseStatus.FORBIDDEN.value());
            response.getWriter().write("{\"code\":" + code + ",\"type\":\"error\",\"message\":\"" + ResponseStatus.resolve(code) + "\"}");
        }


    }
}
